package com.imvc.util;

import java.sql.*;
import java.util.Properties;

/**
 * 数据库资源管理器
 *
 * @author ml
 * @create 2017-10-18--15:39
 */
public class DbResourceManager {
    private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    private static final String JDBC_URL = "jdbc:mysql://localhost:3306/mvc";
    private static final String JDBC_UID = "root";
    private static final String JDBC_PWD = "123";

    private static Driver driver = null;
    private static Properties info = new Properties();

    private DbResourceManager() {
        throw new AssertionError();
    }

    static {
        try {
            loadDriver();
            info.setProperty("user", JDBC_UID);
            info.setProperty("password", JDBC_PWD);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 加载驱动程序
     *
     * @throws Exception
     */
    private static void loadDriver() throws Exception {
        //获取驱动
        driver = (Driver) Class.forName(JDBC_DRIVER).newInstance();
    }

    /**
     * 打开连接
     *
     * @return
     * @throws Exception
     */
    public static Connection getConnection() throws Exception {
        if (driver == null) {
            loadDriver();
        }
        return driver.connect(JDBC_URL, info);
    }

    /**
     * 关闭游标
     *
     * @param rs
     */
    public static void close(ResultSet rs) throws SQLException {
        if (rs != null && !rs.isClosed()) {
            rs.close();
        }
    }

    /**
     * 关闭语句
     *
     * @param stmt
     */
    public static void close(Statement stmt) throws SQLException {
        if (stmt != null && !stmt.isClosed()) {
            stmt.close();
        }
    }

    /**
     * 关闭连接
     *
     * @param con
     */
    public static void close(Connection con) throws SQLException {
        if (con != null && !con.isClosed()) {

            con.close();

        }
    }

    /**
     * 注销驱动
     *
     * @throws SQLException
     */
    public static void unloadDriver() throws SQLException {
        if (driver != null) {
            DriverManager.deregisterDriver(driver);
            driver = null;
        }
    }
}
